package com.guet.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.guet.domain.User;
import com.guet.domain.dto.LoginFormDTO;
import com.guet.domain.dto.UserDTO;
import com.guet.mapper.UserMapper;
import com.guet.service.UserService;
import com.guet.utils.RegexUtils;
import com.guet.utils.Result;
import com.guet.utils.SystemConstants;
import com.guet.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.guet.utils.RedisConstants.*;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public User getById(Long userId) {
        return userMapper.getById(userId);
    }

    @Override
    public Result sendCode(String phone) {
        if(RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误");
        } else {
            String code = RandomUtil.randomNumbers(6);
            stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);
            log.debug("发送验证码成功,验证码:{}",code);
            return Result.ok();
        }
    }

    @Override
    public Result login(LoginFormDTO loginForm) {
        String phone = loginForm.getPhone();
        if(RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号格式错误");
        }

        String code = loginForm.getCode();
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        if(cacheCode == null || !cacheCode.equals(code)){
            return Result.fail("验证码错误");
        }

        User u = userMapper.getByPhone(phone);
        if(u == null){
            // 不存在进行注册
            u = createUserWithPhone(phone);
        }

        // 生成token并将用户信息存到redis
        String token = UUID.randomUUID().toString(true);
        UserDTO userDTO = BeanUtil.copyProperties(u, UserDTO.class);
        // 将用户信息转为Map,并将字段值都转为字符串
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO,new HashMap<>(),
                CopyOptions.create()
                            .setIgnoreNullValue(true)
                            .setFieldValueEditor((fieldName,fieldValue) -> fieldValue.toString()));

        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY + token,userMap);
        stringRedisTemplate.expire(LOGIN_USER_KEY + token,LOGIN_USER_TTL,TimeUnit.MINUTES);
        return Result.ok(token);
    }

    @Override
    public List<User> getByIds(List<Long> ids) {
        List<User> users = userMapper.getByIds(ids);
        return users;
    }

    @Override
    public Result sign() {
        Long userId = UserHolder.getUser().getId();
        LocalDateTime now = LocalDateTime.now();
        // 年和月
        String yearAndMonth = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        // 本月的第几天
        int dayOfMonth = now.getDayOfMonth();

        String key = USER_SIGN_KEY + userId + yearAndMonth;
        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth - 1,true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        Long userId = UserHolder.getUser().getId();
        LocalDateTime now = LocalDateTime.now();
        String yearAndMonth = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        int dayOfMonth = now.getDayOfMonth();
        String key = USER_SIGN_KEY + userId + yearAndMonth;
        // 本月截止今天为止的所有签到记录,返回的是十进制数字
        List<Long> result = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth))
                        .valueAt(0)
        );
        Long num;
        // 没有任何签到结果
        if(result == null || result.isEmpty() ||  result.get(0) == null || (num = result.get(0)) == 0){
            return Result.ok(0);
        }

        int count = 0;
        while (true){
            // 判断最后一位是0或1
            if((num & 1) == 0) {
                break;
            }
            count++;
            num >>>= 1; // 无符号右移
        }
        return Result.ok(count);
    }

    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(SystemConstants.USER_NICK_NAME_PREFIX + RandomUtil.randomString(6));
        user.setPassword("");
        user.setIcon("");
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.save(user);
        return user;
    }
}
